package com.david.fastmsg.utils;

import cn.hutool.core.codec.Base32;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.net.NetUtil;
import com.david.fastmsg.Constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

/**
 * @author qzw
 * @date 2021/9/6
 */
public class Utils {


    public static String getUserId() {
        return UUID.randomUUID().toString().replace("-","");
    }

    public static String getRoomId() {
        return UUID.randomUUID().toString().replace("-","");
    }

    public static String getUserCode() {
        return String.valueOf(System.currentTimeMillis() + new Random().nextInt(1000)).substring(5);
    }

    public static String genFilePath() {
        return getUserCode();
    }

    /**
     * 通过地址获取图片文件信息
     * @return
     */
    public static BufferedImage readImageFile(File file) {
        try{
            BufferedImage image = ImageIO.read(file);
            return image;
        }catch(IOException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过姓名生成文字头像
     * @param userName
     * @return
     */
    public static String generateHead(String userName) {
        String content = String.valueOf(userName.charAt(0));
        String distPath = Utils.genFilePath() + "_" + userName;
        String filePath = distPath + ".jpg";
       // String filePath = Utils.genFilePath() + "_" + userName + ".jpg";
        int width = 40;
        int height = 40;
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        //创建一个画布
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //获取画布的画笔
        Graphics2D g2 = (Graphics2D)bi.getGraphics();

        //开始绘图
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, width, height);
        g2.setPaint(Color.BLACK);
        g2.setFont(new Font("黑体", Font.BOLD, 25));
        //绘制字符串
        g2.drawString(content, 4, 25);

        try {
            //将生成的图片保存为jpg格式的文件。ImageIO支持jpg、png、gif等格式
            ImageIO.write(bi, "jpg", file);
        } catch (IOException e) {
            System.out.println("生成图片出错........");
            e.printStackTrace();
        }
        String suffixName = filePath.substring(filePath.lastIndexOf("."));
        return "/file/preview/" + Base32.encode(distPath) + suffixName;
    }

    public static String generateGroupHead(List<String> userPicList) {
        List<BufferedImage> image = new ArrayList<>();
        for(String userPic: userPicList){
            image.add(loadImageLocal(userPic));
        }
        return writeImageLocal(modifyImagetogeter(handleLarge(88,88, image)));
    }



    private static BufferedImage modifyImagetogeter(List<BufferedImage> image) {
        //创建一个304*304的图片
        BufferedImage tag = new BufferedImage(304,304,BufferedImage.TYPE_INT_RGB);
        try {
            Graphics2D graphics = tag.createGraphics();
            //设置颜色为218，223，224
            graphics.setColor(new Color(218,223,224));
            //填充颜色
            graphics.fillRect(0, 0, 304, 304);
            int count = image.size();
            //根据不同的合成图片数量设置图片放置位置
            if(count == 1){
                int startX = 108;
                int startY = 108;
                BufferedImage b = image.get(0);
                graphics.drawImage(b, startX, startY, b.getWidth(), b.getHeight(), null);
            }else if(count == 2){
                int startX = 60;
                int startY = 108;
                BufferedImage b1 = image.get(0);
                graphics.drawImage(b1, startX, startY, b1.getWidth(), b1.getHeight(), null);
                BufferedImage b2 = image.get(1);
                startX = startX + b1.getWidth()+8;
                graphics.drawImage(b2, startX, startY, b2.getWidth(), b2.getHeight(), null);
            }else if(count == 3){
                int startX = 108;
                int startY = 60;
                BufferedImage b1 = image.get(0);
                graphics.drawImage(b1, startX, startY, b1.getWidth(), b1.getHeight(), null);
                BufferedImage b2 = image.get(1);
                startX = 60;
                startY = 60 + b1.getHeight() + 8;
                graphics.drawImage(b2, startX, startY, b2.getWidth(), b2.getHeight(), null);
                BufferedImage b3 = image.get(2);
                startX = startX + b2.getWidth()+8;
                graphics.drawImage(b3, startX, startY, b3.getWidth(), b3.getHeight(), null);
            }else if(count == 4){
                int startX = 60;
                int startY = 60;
                BufferedImage b1 = image.get(0);
                graphics.drawImage(b1, startX, startY, b1.getWidth(), b1.getHeight(), null);
                BufferedImage b2 = image.get(1);
                startX = 60 + b1.getWidth() + 8;
                graphics.drawImage(b2, startX, startY, b2.getWidth(), b2.getHeight(), null);
                BufferedImage b3 = image.get(2);
                startX = 60;
                startY = 60 + b2.getHeight() + 8;
                graphics.drawImage(b3, startX, startY, b3.getWidth(), b3.getHeight(), null);
                BufferedImage b4 = image.get(3);
                startX = 60 + b3.getWidth() + 8;
                graphics.drawImage(b4, startX, startY, b4.getWidth(), b4.getHeight(), null);
            }else if(count == 5){
                int startX = 60;
                int startY = 60;
                BufferedImage b1 = image.get(0);
                graphics.drawImage(b1, startX, startY, b1.getWidth(), b1.getHeight(), null);
                BufferedImage b2 = image.get(1);
                startX = startX + b1.getWidth()+8;
                graphics.drawImage(b2, startX, startY, b2.getWidth(), b2.getHeight(), null);
                startX = 12;
                startY = 12 + startY + b2.getHeight();
                for(int i = 2;i<count;i++){
                    BufferedImage b = image.get(i);
                    graphics.drawImage(b, startX, startY, b.getWidth(), b.getHeight(), null);
                    startX = startX + b.getWidth() + 8;
                }
            }else if(count == 6){
                int startX = 12;
                int startY = 60;
                for(int i = 0;i<count;i++){
                    BufferedImage b = image.get(i);
                    graphics.drawImage(b, startX, startY, b.getWidth(), b.getHeight(), null);
                    startX = startX + b.getWidth() + 8;
                    if((i+1)%3 == 0){
                        startY = startY + b.getHeight() + 8;
                        startX = 12;
                    }
                }
            }else if(count == 7){
                int startX = 108;
                int startY = 12;
                BufferedImage b = image.get(0);
                graphics.drawImage(b, startX, startY, b.getWidth(), b.getHeight(), null);
                startX = 12;
                startY = startY + 8 + b.getHeight();
                for(int i = 1;i<count;i++){
                    b = image.get(i);
                    graphics.drawImage(b, startX, startY, b.getWidth(), b.getHeight(), null);
                    startX = startX + b.getWidth() + 8;
                    if(i%3 == 0){
                        startY = startY + b.getHeight() + 8;
                        startX = 12;
                    }
                }
            }else if(count == 8){
                int startX = 60;
                int startY = 12;
                BufferedImage b1 = image.get(0);
                graphics.drawImage(b1, startX, startY, b1.getWidth(), b1.getHeight(), null);
                BufferedImage b2 = image.get(1);
                startX = startX + b1.getWidth()+8;
                graphics.drawImage(b2, startX, startY, b2.getWidth(), b2.getHeight(), null);
                startX = 12;
                startY = 12 + b2.getHeight() + 8;
                for(int i = 2;i<count;i++){
                    BufferedImage b = image.get(i);
                    graphics.drawImage(b, startX, startY, b.getWidth(), b.getHeight(), null);
                    startX = startX + b.getWidth() + 8;
                    if(i == 4){
                        startY = startY + b.getHeight() + 8;
                        startX = 12;
                    }
                }
            }else if(count == 9){
                int startX = 12;
                int startY = 12;
                for(int i = 0;i<count;i++){
                    BufferedImage b = image.get(i);
                    graphics.drawImage(b, startX, startY, b.getWidth(), b.getHeight(), null);
                    startX = startX + b.getWidth() + 8;
                    if((i+1)%3 == 0){
                        startY = startY + b.getHeight() + 8;
                        startX = 12;
                    }
                }
            }
            graphics.dispose();
        } catch (Exception e) {
//            logger.error("推送同比压缩图片出错{}",e);
        }

        return tag;
    }

    private static BufferedImage loadImageLocal(String imgName) {
        try {
            String frontPath = imgName.substring(0, imgName.lastIndexOf("."));
            String substring = frontPath.substring(frontPath.lastIndexOf("/") + 1);
            String filePath = Base32.decodeStr(substring) + ".jpg";
            return ImageIO.read(new File(filePath));
        } catch (IOException e) {
//            logger.error("推送同比压缩图片出错{}",e);
        }
        return null;
    }

    private static String writeImageLocal(BufferedImage img) {
        String distPath = Utils.genFilePath();
        String filePath = distPath + ".jpg";
        if (img != null) {
            try {
                File outputfile = new File(filePath);
                ImageIO.write(img, "jpg", outputfile);
            } catch (IOException e) {
//                logger.error("推送同比压缩图片出错{}",e);
            }
        }
        return "/file/preview/" + Base32.encode(distPath) + ".jpg";
    }


    private static List<BufferedImage> handleLarge(Integer width,Integer height,List<BufferedImage> images) {
        List<BufferedImage> b = new ArrayList<>();
        for (BufferedImage image: images) {
            try {
                b.add(zoom2(width, height, image));
            } catch (Exception e) {
//                logger.error("推送同比压缩图片出错{}",e);
            }
        }
        return b;
    }

    private static BufferedImage zoom2(int width,int height,BufferedImage sourceImage) throws Exception {

        if( sourceImage == null ){
            return sourceImage;
        }
        // 计算x轴y轴缩放比例--如需等比例缩放，在调用之前确保參数width和height是等比例变化的
        double ratiox  = (new Integer(width)).doubleValue()/ sourceImage.getWidth();
        double ratioy  = (new Integer(height)).doubleValue()/ sourceImage.getHeight();
        AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratiox, ratioy), null);
        BufferedImage bufImg = op.filter(sourceImage, null);
        return bufImg;
    }

    public static String convertDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        return sdf.format(date);
    }
}
